package com.thoughtworks.mobinium.parser;

import org.antlr.runtime.tree.Tree;

public class AstProcessor {

	private static final String APPLICATION = "application";
	private static final String SELECT = "select";
	private static final String PRESS = "press";
	private static final String CHOOSE = "choose";
	private static final String TYPE = "type";
	private static final String ASSERT = "assert";

	private static final String[] TOKENS = { APPLICATION, SELECT, PRESS, TYPE,
			ASSERT, CHOOSE };

	private ScriptVisitor visitor;

	public AstProcessor(ScriptVisitor visitor) {
		this.visitor = visitor;
	}

	public void accept(Tree ast) {
		for (int i = 0; i < ast.getChildCount(); i++) {
			Tree child = ast.getChild(i);
			if (isToken(child.getText())) {
				invokeVisit(child);
			}
		}
	}

	private boolean isToken(String text) {
		for (String token : TOKENS) {
			if (token.equals(text)) {
				return true;
			}
		}
		return false;
	}

	private void invokeVisit(Tree node) {
		String currentToken = stripQuotes(node.getText());
		if (APPLICATION.equals(currentToken)) {
			visitor.visitApplication(stripQuotes(node.getChild(0).getText()));
		}
		if (SELECT.equals(currentToken)) {
			visitor.visitSelect(stripQuotes(node.getChild(0).getText()),
					stripQuotes(node.getChild(1).getText()));
		}
		if (CHOOSE.equals(currentToken)) {
			visitor.visitChoose(stripQuotes(node.getChild(0).getText()),
					stripQuotes(node.getChild(1).getText()));
		}
		if (PRESS.equals(currentToken)) {
			visitor.visitPress(stripQuotes(node.getChild(0).getText()));
		}
		if (TYPE.equals(currentToken)) {
			visitor.visitType(stripQuotes(node.getChild(0).getText()),
					stripQuotes(node.getChild(1).getText()));
		}
		if (ASSERT.equals(currentToken)) {
			visitor.visitAssertion(stripQuotes(node.getChild(0).getText()),
					stripQuotes(node.getChild(1).getText()));
		}
	}

	private String stripQuotes(String text) {
		if (text.startsWith("\"") && text.length() > 2) {
			return text.substring(1, text.length() - 1);
		}
		return text;
	}
}
